#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   dhcp_service.sh
# Version:    1.0
# Date:       2013/09/22
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-04网络服务-07DHCP-03静态IP分配
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/10/08
#             - setup dhcpd.conf, start dhcpd service, and assign static IP to clients.
# ----------------------------------------------------------------------
##! @TODO:  update dhcpd.conf
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup()
{
    trap do_cleanup INT EXIT
    RHOST=${RHOST}

    # get local ip
    local LOCAL_IP=`ifconfig  | grep 'inet ' | grep -m 1 -v '127.0.0.1'  | awk '{print $2}' | tr -d "addr:"`

    # get network IP
    local NET_ID=`echo ${LOCAL_IP} | awk 'BEGIN{OFS=FS="."}{print $1,$2,$3}'`    

    ping -c 1 ${DHCPSTATICIP} | grep -i "Destination Host Unreachable"
    if [ $? -eq 0 ]
    then
        echo "pass : ${DHCPSTATICIP} not used"
    else
        echo "fail : ${DHCPSTATICIP} used, pls check"
        exit 1
    fi


    serv="dhcpd"
    DHCP_CONF="/etc/dhcp/dhcpd.conf"

    if [ -r ${DHCP_CONF} ]
    then
        mv ${DHCP_CONF} ${DHCP_CONF}.bak
        EchoResult "backup ${DHCP_CONF}"
    else
        echo "${DHCP_CONF} not exists, pls check"
        exit 1
    fi

    # setup dhcpd.conf
    if [ "x" != "${NET_ID}x" ];then
    cat > ${DHCP_CONF} <<-EOF
subnet ${NET_ID}.0 netmask 255.255.255.0{
range ${NET_ID}.160 ${NET_ID}.170;
default-lease-time 6000;
max-lease-time 7200;
option time-offset -3600;
}
host node1{
hardware ethernet ${HWADDRST};
fixed-address ${DHCPSTATICIP};
}
EOF
    else
        echo "net id is null, pls check"
        exit 1
    fi

    # start dhcpd service
    restart_daemon ${serv} 
    sleep 5
    netstat -ntulp | grep ${serv}
    EchoResult "${serv} restart"


}

##! @TODO:  start and stop dhcpd service.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_test()
{
    echo "Test: assign static IP to clients."    

    ${RSH} -l root -n ${RHOST} "ps aux | grep dhclient | grep -v grep && killall dhclient"
    ${RSH} -l root -n ${RHOST} "/sbin/dhclient" &

    sleep 45
    killall ${RSH}


    # get ip from log
    DHCPACK=`tail -5 /var/log/messages | grep ${DHCPSTATICIP}`
    DYNAMIC_IP=`echo ${DHCPACK#*DHCPACK} | awk '{print $2}'`
    if [ -z ${DYNAMIC_IP} ]
    then
        echo "dynamic ip null, pls check"
        exit 1
    else
        echo "dynamic ip: ${DYNAMIC_IP}"
    fi

    # get hwaddr from log
    HWADDR=`echo ${DHCPACK#**to} | awk '{print $1}' | tr A-Z a-z`

    ping -c 1 ${DYNAMIC_IP} | grep -i "Destination Host Unreachable"
    if [ $? -ne 0 ]
    then
        echo "pass : ping ${DYNAMIC_IP}"
    else
        echo "fail : ping ${DYNAMIC_IP}"
        exit 1
    fi

    ARP_D=`arp -D ${DYNAMIC_IP} | awk '{print $3}' | tail -1`
    test "${HWADDR}" = "${ARP_D}"
    EchoResult "Testcase: dhcp server with static ip"

}

##! @TODO:  cleanup tmp files, back up dhcpd.conf and stop dhcp service.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_cleanup()
{
    stop_daemon ${serv}
    [ -f ${DHCP_CONF}.bak ] && mv -f ${DHCP_CONF}.bak ${DHCP_CONF}

    RHOST=${DHCPSTATICIP}
    expect <<-END
    spawn ssh -tt -n $RHOST "ps aux | grep dhclient | grep -v grep && /usr/bin/killall dhclient; \
                         test -f /bin/systemctl  && /bin/systemctl restart network.service || /sbin/service network restart"

        expect {
                "yes/no" {
                send "yes\r"
                exp_continue
                }

                "password: " { 
                     send "$PASSWORD\r"
                     expect "Permission denied" { send_user "ssh $RHOST failed\r"; exit 1; }
                     }

            }

END

    sleep 10

    ping -c 1 $RHOST
    if [ $? -ne 0 ];then
        echo -e "\033[32m PASS\033[0m | network restore"
    else
        echo -e "\033[31m FAIL\033[0m | network restore failed."
        exit 1
    fi



}
# include lib files

if [ -z "$SFROOT" ]
then
    CMDLIB=./
    SFROOT=./
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/XmlParse.sh
. ${CMDLIB}/lib/Net.sh

. ${CMDLIB}/setup.sh

# get RHOST, RUSERNAME, PASSWORD from config.xml
DATA_FILE="${SFROOT}/testcases/Network_Service/config.xml"
[ -e $DATA_FILE ] || { echo "$DATA_FILE not find, test end."; exit 1; }

XmlParse ${DATA_FILE}

GetValue REHOST ReHost
GetValue RUSERNAME UserName
GetValue PASSWORD RootPasswd

# get static ip and hwaddr from config.xml
GetValue DHCPSTATICIP DhcpStaticIp
GetValue HWADDRST HWAddr

export RHOST=${REHOST}
export RUSERNAME=${RUSERNAME}
export PASSWORD=${PASSWORD}


setup_env || { echo "setup env failed, test end."; exit 1; }

do_setup
do_test || { echo "testcase failed."; exit 1; }
